<template>
  <div>
      <div class="card" >
          <el-input clearable style="width: 260px; margin-right: 5px" v-model="data.name" placeholder="请输入用户名查询" :suffix="Search"></el-input>
          <el-input clearable style="width: 260px; margin-right: 5px" v-model="data.sex" placeholder="请输入性别查询" :suffix="Search"></el-input>
          <el-button type="primary" icon="Search" @click="userpage"/>
          <el-button @click="reset">重置</el-button>
      </div>
      <div class="card" >
          <el-button type="primary" @click="handleAdd">新 增</el-button>
          <el-button type="danger" @click="deleteBatch">批量删除</el-button>
          <el-button type="info" @click="exportData">批量导出</el-button>

          <el-upload style="display: inline-block;margin-left: 10px"
                     action="http://localhost:8848/user/import"
                     :show-file-list="false"
                     :on-success="handleImportSuccess">
              <el-button type="success" >批量导入</el-button>
          </el-upload>
      </div>

      <div class="card" >
          <el-table :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
                    :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }">
              <el-table-column type="selection" width="30" />
              <el-table-column label="头像" width="80px">
                <template #default="scope">
                    <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" :preview-teleported="true"
                    style="width: 50px; height: 50px; border-radius: 50%; display:block "/>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="名称"  />
              <el-table-column prop="sex" label="性别"  />
              <el-table-column prop="age" label="年龄"  />
              <el-table-column prop="phone" label="电话" />
              <el-table-column prop="address" label="地址" />
              <el-table-column prop="birthday" label="生日" />
              <el-table-column prop="password" label="密码" />
              <el-table-column prop="email" label="邮箱" width="200" />
              <el-table-column label="操作" >
                  <template #default="scope">
                      <el-button type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
                      <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
                  </template>
              </el-table-column>
          </el-table>
      </div>
      <div class="card">
          <el-pagination
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              layout="total, sizes,prev, pager, jumper"
              :total="data.total"
              @current-change="userpage"
              @size-change="userpage"
          />
      </div>
  </div>

    <!-- 添加表单弹窗 -->
    <el-dialog v-model="data.formVisible" title="用户信息" width="500" distory-on-close>
        <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px">
            <el-form-item prop="name" label="用户名" >
                <el-input v-model="data.form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="sex" label="性别" >
                <el-input v-model="data.form.sex" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="age" label="年龄" >
                <el-input v-model="data.form.age" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="phone" label="电话号码" >
                <el-input v-model="data.form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="address" label="地址" >
                <el-input v-model="data.form.address" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="birthday" label="生日" >
                <el-input v-model="data.form.birthday" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="password" label="密码" >
                <el-input v-model="data.form.password" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="email" label="邮箱地址" >
                <el-input v-model="data.form.email" autocomplete="on" />
            </el-form-item>
            <el-form-item label="头像" >
                <el-upload
                    action="http://localhost:8848/files/upload"
                    :headers = "{token:data.user.token}"
                    :on-success="handleAvatarSuccess"
                    list-type="picture"
                >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>


        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="data.formVisible = false">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import {Plus, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {reactive, ref} from "vue";

const data = reactive({
    user: JSON.parse(localStorage.getItem('userInfo')),
    name: null,
    pageNum: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    formVisible:false,
    form:{},
    rules: {
        name: [
            { required: true, message: "请填写用户名", trigger: "blur" }
        ],
        sex: [
            { required: true, message: "请填写性别", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请填写密码", trigger: "blur" }
        ]
    },
    rows:[]
})
const  formRef = ref()
const userpage = () =>{
    request.get('/user/selectPage',{
        params:{
            pageNum:data.pageNum,
            pageSize:data.pageSize,
            name: data.name,
            sex: data.sex
        }
}).then(res =>{
        if(res.code == '200') {
            data.tableData = res.data.list
            data.total = res.data.total
        }else {
            ElMessage.error(res.msg)
        }
    })
}
userpage()

const reset = () =>{
    data.name = null
    data.sex = null
    userpage()
}

const handleAvatarSuccess = (res) => {
    data.form.avatar = res.data
    ElMessage.success('头像上传成功')
}

const save = () => {
    data.form.id ? update() : add()
}
const handleAdd = () => {
    data.formVisible = true
    data.form = {}
}
const add = () =>{
    formRef.value.validate((valid) =>{
        if(valid) {
            request.post('/user/add',data.form).then(res =>{
                if(res.code == '200') {
                    data.formVisible = false
                    ElMessage.success('新增成功')
                    userpage()
                }else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}
const update = () => {
    //forRef 是表单的引用
    formRef.value.validate((valid) =>{
        if(valid) {
            request.put('/user/update',data.form).then(res =>{
                if(res.code == '200') {
                    data.formVisible = false
                    ElMessage.success('修改成功')
                    userpage()
                }else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })

}
const handleEdit = (row) => {
    data.form = JSON.parse(JSON.stringify(row))  //深度拷贝数据
    data.formVisible = true
}

const del = (id) => {
    ElMessageBox.confirm('删除后无法恢复，是否确认删除？', '删除确认',{type: 'waring'}).then(res =>{
        request.delete('/user/delete/' + id).then(res => {
            if (res.code == '200') {
                ElMessage.success('删除成功')
                userpage()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {'已取消删除'})
}

const handleSelectionChange = (rows) =>{  //实际选择的行组成的数组
    console.log(rows)
    data.rows = rows
}
const deleteBatch = () => {
    if(data.rows.length === 0){
        ElMessage("请选择数据")
        return
    }
    ElMessageBox.confirm('❗删除后无法恢复，是否确认删除？', '删除确认').then(res =>{
        request.delete('/user/deleteBatch',{data: data.rows }).then(res => {
            if (res.code == '200') {
                ElMessage.success('批量删除成功')
                userpage()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {'已取消删除'})
}

const exportData = () => {
    let url = `http://localhost:8848/user/export?name=${data.name == null ? '' : data.name}`
    window.open(url)
}

const handleImportSuccess = () => {
    ElMessage.success("批量导入成功")
    userpage()
}

</script>